package cn.youdian.core.util;

import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.util.Locale;

/**
 * 加密解密工具
 *
 * @author K.J
 * @date 2021.05.29 22:40:09
 */
public class SecurityUtils {


    /**
     * 生成hmac-sha512
     * @param str
     * @return
     */

    public static String hmacSHA512(String str, String key) {
        // TODO Auto-generated method stub
        Digest digest = new SHA512Digest();
        HMac hmac = new HMac(digest);

        byte[] keyBytes = key.getBytes();
        hmac.init(new KeyParameter(keyBytes));
        hmac.update(str.getBytes(), 0, str.getBytes().length);
        byte[] byteFinal = new byte[hmac.getMacSize()];
        hmac.doFinal(byteFinal, 0);

        return convertByteToHexString(byteFinal);
    }

    public static String convertByteToHexString(byte[] bytes) {
        // TODO Auto-generated method stub
        StringBuffer r = new StringBuffer();
        int l = bytes.length;
        for (int i = 0; i < l; i++) {
            int temp = bytes[i] & 0xff;
            String tempHex = Integer.toHexString(temp);
            if (tempHex.length() < 2) {
                r.append("0");
                r.append(tempHex);
            } else {
                r.append(tempHex);
            }
        }
        return r.toString();
    }

    public static byte[] convertHexStringToByte(String str) {
        /* 对输入值进行规范化整理 */
        str = str.trim().replace(" ", "").toUpperCase(Locale.US);
        // 处理值初始化
        int m = 0, n = 0;
        int iLen = str.length() / 2; // 计算长度
        byte[] ret = new byte[iLen]; // 分配存储空间

        for (int i = 0; i < iLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = (byte) (Integer.decode("0x" + str.substring(i * 2, m) + str.substring(m, n)) & 0xFF);
        }
        return ret;
    }

    /**
     * 根据参数生成KEY
     */

    public static Key toKey(String strKey, String keyType) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(keyType);
            return keyFactory.generateSecret(new DESKeySpec(strKey.getBytes("UTF8")));
        } catch (Exception e) {
            throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);
        }
    }
}
